<?php
	//Connect to database
	require_once $_SERVER['DOCUMENT_ROOT'] . '/deviantpic/inc/database.php';

	//Call function based on action
	if (isset($_POST['action'])) {
		if ($_POST['action'] == "send")		send_message();
		if ($_POST['action'] == "receive")	get_messages();
	}

	function send_message() {
		//Do nothing if no data
		if (!isset($_POST['sender']) || !isset($_POST['receiver']) || !isset($_POST['message'])) echo "";
		else {
			//Insert row
			mysql_query("INSERT INTO chats (sender_id, receiver_id, message) VALUES (" .
					$_POST['sender'] . ", " . $_POST['receiver'] . ", '" . $_POST['message'] . "')") or die(mysql_error());

			//Get name
			$sender_name	= "";
			$result			= mysql_query("SELECT username FROM users WHERE id=" . $_POST['sender']) or die(mysql_error());
			if (mysql_num_rows($result) >= 1) {
				$row			= mysql_fetch_array($result);
				$sender_name	= $row['username'];
				$messages		= array();
				$messages[]		= $_POST['message'];
				create_chat($sender_name, $messages);
			} else echo "";
		}
	}

	function get_messages() {
		//Do nothing if no data
		if (!isset($_POST['sender']) || !isset($_POST['receiver'])) echo "";
		else {
			//Get name
			$sender_name	= "";
			$result			= mysql_query("SELECT username FROM users WHERE id=" . $_POST['sender']) or die(mysql_error());
			if (mysql_num_rows($result) >= 1) {
				$row			= mysql_fetch_array($result);
				$sender_name	= $row['username'];
			}

			//Prepare array
			$chat_ids		= array();
			$chat_messages	= array();

			//Query
			$result = mysql_query("SELECT * FROM chats WHERE sender_id=" . $_POST['sender'] . " AND receiver_id=" . $_POST['receiver'] . " AND been_read=0") or die(mysql_error());
			if (mysql_num_rows($result) >= 1) {
				//Get result
				$row = mysql_fetch_array($result);
				while ($row) {
					//Get data
					$chat_ids[]			= $row['id'];
					$chat_messages[]	= $row['message'];
					$row				= mysql_fetch_array($result);
				}

				//Message is now read
				foreach ($chat_ids as $chat_id)
					mysql_query("UPDATE chats SET been_read='1' WHERE id='" . $chat_id . "'") or die(mysql_error());

				//Create chat message
				create_chat($sender_name, $chat_messages);
			} else echo "";
		}
	}

	function create_chat($name, $messages) {
		//For each message
		foreach ($messages as $message) {
?>

	<div class="chat-block">
		<span class="chat-user">
			<?php echo "$name: "; ?>
		</span>
		<span class="chat-message">
			<?php echo $message; ?>
		</span>
	</div>

<?php 
		}
	}
?>
